import Vue from 'vue'
import Vuex from 'vuex'
import api from '@/api'
import site from '@/config/site'
Vue.use(Vuex)

const store = new Vuex.Store({
  state: {
    mask: false,
    model: 'key',
    searchBar: {
      key: '交通'
    },
    key: {
      list: [],
      hotWords: [],
      linkWords: [],
      counts: 0,
      page: 1,
      perPage: 10
    },
    quiz: {},
    learn: {},
    card: {},
    exam: {},
    loading: false,
    toast: '',
    doc: {
      title: '',
      content: ''
    }
  },
  mutations: {
    updateSearchBar (state, payload) {
      state.searchBar[state.model] = payload
    },
    updateMask (state, payload) {
      state.mask = payload
    },
    updateModel (state, payload) {
      state.model = payload
    },
    updatePage (state, payload) {
      let model = state.model
      state[model].page = payload
    },
    updateToast (state, payload) {
      state.toast = payload
    },
    updateLoading (state, payload) {
      state.loading = payload
    },
    updateKey (state, payload) {
      if (!payload || !payload.data) { return }
      let {
        doc_infos: list = [],
        hotspots: hotWords = [],
        related_words: linkWords = [],
        total_count: counts = 0
      } = payload.data
      hotWords = hotWords.slice(0, 30)
      linkWords = linkWords.slice(0, 30)
      let data = {
        list,
        hotWords,
        linkWords,
        counts
      }
      state.key = Object.assign(state.key, data)
    },
    updateDoc (state, payload) {
      state.doc = Object.assign(state.doc, payload)
    }
  },
  actions: {
    toast ({ commit }, payload) {
      commit('updateToast', payload)
      setTimeout(() => commit('updateToast', ''), 1000)
    },
    async seachFromBar ({ dispatch, commit, state }, payload) {
      let msgTmp = state.searchBar[state.model]
      let msg = msgTmp.trim()
      if (!msg) { return dispatch('toast', '请输入查询内容') }
      commit('updateLoading', true)
      let type = site.searchConfig[state.model]
      let res = await api[type](msg, state.key.page, state.key.perPage)
      if (res && res.data) {
        switch (type) {
          case 11:
            commit('updateKey', res)
            break
        }
      }
      commit('updateLoading', false)
      console.log(res, this.apiType)
    },
    pageChange ({ dispatch, commit, state }, payload) {
      commit('updatePage', payload)
      dispatch('seachFromBar')
    },
    showDoc ({ dispatch, commit, state }, payload) {
      commit('updateLoading', true)
      let title = payload
      api[13]('CJJ 58-1994 城镇供水厂运行、维护及安全技术规程-一级').then(res => {
        let data = res && res.data && res.data.raw_text
        if (data) {
          commit('updateMask', true)
          let content = data.replace(/\n|\r/g, '<br>')
          let doc = {
            title,
            content
          }
          commit('updateDoc', doc)
        }
        commit('updateLoading', false)
      })
    }
  }
})

export default store
